package com.ftg.learn.service;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 文本生成视频服务类
 * @author 布衣
 */
@Service
public class TextToVideoService {

    @Value("${langchain4j.open-ai.chat-model.api-key}")
    private String apiKey;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public TextToVideoService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    /**
     * 根据文本生成视频
     * @param prompt 文本提示词
     * @param size 视频分辨率，如 "1920*1080"
     * @return 任务ID
     */
    public String generateVideoTask(String prompt, String size) throws Exception {
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);
        headers.set("X-DashScope-Async", "enable");

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "wanx2.1-t2v-plus");

        Map<String, Object> input = new HashMap<>();
        input.put("prompt", prompt);
        requestBody.put("input", input);

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("size", size);
        requestBody.put("parameters", parameters);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            JsonNode jsonNode = objectMapper.readTree(response.getBody());
            return jsonNode.get("output").get("task_id").asText();
        } else {
            throw new RuntimeException("Failed to create video generation task: " + response.getBody());
        }
    }

    /**
     * 根据任务ID查询视频生成结果
     * @param taskId 任务ID
     * @return 视频URL或任务状态
     */
    public Map<String, String> getVideoResult(String taskId) throws Exception {
        String url = "https://dashscope.aliyuncs.com/api/v1/tasks/" + taskId;

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);

        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

        Map<String, String> result = new HashMap<>();

        if (response.getStatusCode() == HttpStatus.OK) {
            JsonNode jsonNode = objectMapper.readTree(response.getBody());
            String taskStatus = jsonNode.get("output").get("task_status").asText();
            result.put("taskStatus", taskStatus);

            if ("SUCCEEDED".equals(taskStatus)) {
                String videoUrl = jsonNode.get("output").get("video_url").asText();
                result.put("videoUrl", videoUrl);
            } else if ("FAILED".equals(taskStatus)) {
                result.put("error", "Video generation failed");
            }
        } else {
            throw new RuntimeException("Failed to get video generation result: " + response.getBody());
        }

        return result;
    }
}

